package com.itheima.app.manager;

import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.SetPhone;
import com.itheima.domain.db.User;
import com.itheima.service.db.UserService;
import com.itheima.vo.ErrorResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
public class UserPhoneManager {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    UserService userService;

    /**
     * 发送验证码
     */
    public void sendVerificationCode() {

        Long userId = UserHolder.get().getId();

        User user = userService.findByUserId(userId);

        String phone = user.getMobile();

        String code = "123456";

        stringRedisTemplate.opsForValue().set("user_setPhone_code:"+phone,code, Duration.ofMinutes(1));

    }

    /**
     * 校验验证码
     * @param verificationCode 验证码
     * @return 是否正确
     */
    public ResponseEntity checkVerificationCode(String verificationCode) {

        Long userId = UserHolder.get().getId();

        User byUserId = userService.findByUserId(userId);

        String redisCode = stringRedisTemplate.opsForValue().get("user_setPhone_code:" + byUserId.getMobile());

        boolean flag = StrUtil.equalsIgnoreCase(verificationCode, redisCode);

        if (flag) {
            stringRedisTemplate.delete("user_setPhone_code:" + byUserId.getMobile());
            SetPhone setPhone = new SetPhone();
            setPhone.setVerification(flag);
            return ResponseEntity.ok(setPhone);

        }else {

            return ResponseEntity.status(500).body("验证码输入错误，请重新输入");
        }

    }

    /**
     * 保存新手机号
     * @param phone
     * @return
     */
    public ResponseEntity setPhone(String phone) {
        User user = UserHolder.get();
        user.setMobile(phone);
        if (userService.findByPhone(phone)!=null){
            return ResponseEntity.status(500).body(ErrorResult.mobileError());
        }
        userService.update(user);
        return ResponseEntity.ok(null);
    }
}
